var status = 0;
var 红色箭头 = "#fUI/UIWindow/Quest/icon6/7#";
var opt = 0;

// 各种强化模式的金叶子消耗系数
var GLEAF_NORMAL = 1 // 普通
var GLEAF_CURSED = 0.3 // 诅咒
var GLEAF_CHAOS = 0.7 // 混沌
var GLEAF_BLESS = 1.5 // 祝福
// 各种强化模式最终消耗的金叶子
var needNormal = 30
var needCursed = 60
var needChaos = 60
var needBless = 100

// 各种强化模式概率的系数
var PROBABILITY_NORMAL = 1
var PROBABILITY_CURSED = 1.5
var PROBABILITY_CHAOS = 1.2
var PROBABILITY_BLESS = 2
// 各种强化模式最终的概率
var probabilityNormal = 0.1
var probabilityCursed = 0.1
var probabilityChaos = 0.1
var probabilityBless = 0.1

// 祝福卷轴
var needBlessScroll = 10

function start() {
    status = -1;
    action(1, 0, 0);
}

function action(mode, type, selection) {
    if (mode == -1) {
        cm.dispose();
    } else {
        if (status >= 0 && mode == 0) {
            cm.dispose();
            return;
        }
        if (mode == 1)
            status++;
        else
            status--;
    }

    var goldenLeaf = 4000313

    var eraserMuyao     = 4001038
    var eraserMogu      = 4001039
    var eraserHouzi     = 4001040
    var eraserYouling   = 4001041
    var eraserShuiling  = 4001042
    var eraserZhangyu   = 4001043

    var iconMuyao       = "#v" + eraserMuyao + "#"
    var iconMogu        = "#v" + eraserMogu + "#"
    var iconHouzi       = "#v" + eraserHouzi + "#"
    var iconYouling     = "#v" + eraserYouling + "#"
    var iconShuiling    = "#v" + eraserShuiling + "#"
    var iconZhangyu     = "#v" + eraserZhangyu + "#"
    
    var displayGoldenMaple = "#v" + goldenLeaf + "##z" + goldenLeaf + "#"
    var displayMuyao    = "#v" + eraserMuyao + "##z" + eraserMuyao + "#"
    var displayMogu     = "#v" + eraserMogu + "##z" + eraserMogu + "#"
    var displayHouzi    = "#v" + eraserHouzi + "##z" + eraserHouzi + "#"
    var displayYouling  = "#v" + eraserYouling + "##z" + eraserYouling + "#"
    var displayShuiling = "#v" + eraserShuiling + "##z" + eraserShuiling + "#"
    var displayZhangyu  = "#v" + eraserZhangyu + "##z" + eraserZhangyu + "#"

	if (status == 0) {
        var text = "你好#b#h ##k，我是本服装备加卷次数管理员。请把要加卷的装备放在装备栏#r<第一格>#k\r\n\r\n"
        cm.sendNext(text);
    } else if (status == 1) {
        var provider = Packages.server.MapleItemInformationProvider.getInstance();
        var item = cm.getInventory(1).getItem(1);
        if (item == null) {
            cm.sendOk("对不起,你装备栏第一格没有装备!");
            cm.dispose();
        } else if (provider.isCash(item.getItemId()) == true) {
            cm.sendOk("商城点卷物品暂不支持.");
            cm.dispose();
        } else {
            cm.sendYesNo("请确认一下你的装备是：#v" + item.getItemId() + "##b#z" + item.getItemId() + "##k吗？\r\n#r（注意：不能强化的装备请不要加卷，即使成功次数也不会增加）#k");
        }
    } else if (status == 2) {
        var item = cm.getChar().getInventory(Packages.client.inventory.MapleInventoryType.EQUIP).getItem(1).copy();
        var itemName = cm.getItemName(item.getItemId())
        var lvSlots = item.getLevel()
        var slots = item.getUpgradeSlots()
        var hammer = item.getViciousHammer()
        var totalSlots = lvSlots + slots - hammer // 未砸卷+已砸卷-金锤子提高的总次数
        var itemLv = cm.getItemLevel(item.getItemId())
        // 装备等级最小为50，小于50的全部按50来算
        itemLv = Math.max(itemLv, 50)
        /* 计算所需的金叶子数量，公式为
        装备系数 = 装备等级 / 18
        砸卷系数 = max(砸卷总次数-7, 1)^2
        影响叶子系数 = (砸卷系数)^2
        基础金叶子数量 = (装备系数 + 影响叶子系数)^2 / 3
        最终金叶子数量 = max(基础数量, 30)
        然后再处理各种模式最终数量
        */
        var equipCFT = itemLv / 18.0
        var slotsCFT = Math.max(totalSlots-7, 1)
        var upLeafCFT = Math.pow(slotsCFT, 2)
        var needLeaf = Math.pow((equipCFT + upLeafCFT), 2) / 3
        needNormal = Math.ceil(Math.max(needLeaf * GLEAF_NORMAL, 30))
        needCursed = Math.ceil(Math.max(needLeaf * GLEAF_CURSED, 60))
        needChaos = Math.ceil(Math.max(needLeaf * GLEAF_CHAOS, 60))
        needBless = Math.ceil(Math.max(needLeaf * GLEAF_BLESS, 80) + (needLeaf * 0.5))
        /* 计算成功概率，公式为
        强化系数 = max(总砸卷次数-3, 1)
        概率系数 = (强化系数)^2 * 0.1
        基础概率 = 1 / 概率系数
        最终概率 = max(min(基础概率 * 模式概率, 100), 0.01)
        然后再处理各种模式最终概率
        */
        var upSlotCFT = Math.max(totalSlots-3, 1) // 强化系数
        var upChanceCFT = Math.pow(upSlotCFT, 2) * 0.1
        var probability = 1 / upChanceCFT
        probability = Math.max(Math.min(probability, 1), 0.0001)
        probabilityNormal = probability * PROBABILITY_NORMAL
        probabilityCursed = Math.min(probability * PROBABILITY_CURSED, 0.3)
        probabilityChaos = Math.min(probability * PROBABILITY_CHAOS, 0.3)
        probabilityBless = Math.min(probability * PROBABILITY_BLESS, 0.5)

        var text = "请选择要进行哪种强化：\r\n"
        var btn1 = "#L1##e<普通加卷> #n#b" + needNormal + "个" + displayGoldenMaple + "，#r" + (probabilityNormal*100).toFixed(2) + "%成功率#k，成功后增加装备#r1次#k砸卷次数\r\n"
        var btn2 = "#L2##e<诅咒加卷> #n#b" + needCursed + "个" + displayGoldenMaple + " #k+ （" + iconMuyao + iconMogu + iconHouzi + iconShuiling + iconYouling + iconZhangyu + "）橡皮擦的其中一个，#r" + (probabilityCursed*100).toFixed(2) + "%成功率#k，成功后随机增加#r1~5次#k砸卷次数。#r失败时50%概率会使装备损坏，请谨慎使用#k\r\n"
        var btn3 = "#L3##e<混沌加卷> #n#b" + needChaos + "个" + displayGoldenMaple + " #k+ （" + iconMuyao + iconMogu + iconHouzi + iconShuiling + iconYouling + iconZhangyu + "）橡皮擦的其中一个，#r" + (probabilityChaos*100).toFixed(2) + "%成功率#k，成功后增加装备#r1次#k砸卷次数。#r失败时装备所有属性随机波动[-10 ~ +5]#k\r\n"
        text += btn1 + btn2 + btn3
        cm.sendSimple(text)
    } else if (status == 3) {
        // 选择普通强化
        if(selection == 1) {
            if(cm.haveItem(goldenLeaf, needNormal)) {
                cm.gainItem(goldenLeaf, -needNormal);

                var item = cm.getChar().getInventory(Packages.client.inventory.MapleInventoryType.EQUIP).getItem(1).copy();
                var itemName = cm.getItemName(item.getItemId())
                var lvSlots = item.getLevel()
                var slots = item.getUpgradeSlots()
                var totalSlots = lvSlots + slots // 未砸卷+已砸卷的总次数

                var chance = Math.random();
                if (chance < probabilityNormal) {
                    item.setUpgradeSlots((item.getUpgradeSlots() + 1));
                    totalSlots += 1
                    Packages.server.MapleInventoryManipulator.removeFromSlot(cm.getC(), Packages.client.inventory.MapleInventoryType.EQUIP, 1, 1, false);
                    Packages.server.MapleInventoryManipulator.addFromDrop(cm.getC(), item, false);
                    cm.sendOk("恭喜你加卷成功！");
                    cm.喇叭(1, "恭喜玩家["+ cm.getName() + "]装备普通加卷+1成功！获得了装备<" + itemName + "+" + totalSlots + ">");
                } else {
                    cm.sendOk("很遗憾，你的加卷失败了……")
                    cm.喇叭(1, "很遗憾，玩家["+ cm.getName() + "]装备普通加卷失败……");
                }
            } else {
                cm.sendOk("你的#b" + displayGoldenMaple + "#k不足！");
            }
            cm.dispose()

        // 诅咒或混沌选择橡皮擦
        } else if (selection == 2 || selection == 3) {
            var needG = 100
            if (selection == 2) {
                opt = 2 
                needG = needCursed
            } else if (selection == 3) { 
                opt = 3 
                needG = needChaos
            }

            if( cm.haveItem(goldenLeaf, needG) ){
                var text = "选择消耗的橡皮擦：\r\n"
                text += "#L1##b" + displayMuyao + "#k（剩余：" + cm.getPlayer().itemQuantity(eraserMuyao) + "个）\r\n"
                text += "#L2##b" + displayMogu + "#k（剩余：" + cm.getPlayer().itemQuantity(eraserMogu) + "个）\r\n"
                text += "#L3##b" + displayHouzi + "#k（剩余：" + cm.getPlayer().itemQuantity(eraserHouzi) + "个）\r\n"
                text += "#L4##b" + displayYouling + "#k（剩余：" + cm.getPlayer().itemQuantity(eraserYouling) + "个）\r\n"
                text += "#L5##b" + displayShuiling + "#k（剩余：" + cm.getPlayer().itemQuantity(eraserShuiling) + "个）\r\n"
                text += "#L6##b" + displayZhangyu + "#k（剩余：" + cm.getPlayer().itemQuantity(eraserZhangyu) + "个）\r\n"
                cm.sendNext(text)
            } else {
                cm.sendOk("你的#b" + displayGoldenMaple + "#k不足！");
                cm.dispose()
            }
        }
        
    // 诅咒或混沌
    } else if (status == 4) {
        // 诅咒加卷
        if(opt == 2)
        {
            // 设置用户选择的橡皮擦
            var selEraser = eraserMuyao
            if(selection == 1) { selEraser = eraserMuyao }
            else if(selection == 2) { selEraser = eraserMogu }
            else if(selection == 3) { selEraser = eraserHouzi }
            else if(selection == 4) { selEraser = eraserYouling }
            else if(selection == 5) { selEraser = eraserShuiling }
            else if(selection == 6) { selEraser = eraserZhangyu }

            if( cm.haveItem(goldenLeaf, needCursed) && cm.haveItem(selEraser, 1) ) {
                cm.gainItem(goldenLeaf, -needCursed);
                cm.gainItem(selEraser, -1);
                
                var item = cm.getChar().getInventory(Packages.client.inventory.MapleInventoryType.EQUIP).getItem(1).copy();
                var itemName = cm.getItemName(item.getItemId())
                var lvSlots = item.getLevel()
                var slots = item.getUpgradeSlots()
                var totalSlots = lvSlots + slots // 未砸卷+已砸卷的总次数

                var chance = Math.random();
                if (chance < probabilityCursed) {
                    var rand = Math.random() * 5 + 1
                    var count = Math.floor(rand)
                    // 随机加1~5
                    item.setUpgradeSlots((item.getUpgradeSlots() + count));
                    totalSlots += count
                    Packages.server.MapleInventoryManipulator.removeFromSlot(cm.getC(), Packages.client.inventory.MapleInventoryType.EQUIP, 1, 1, false);
                    Packages.server.MapleInventoryManipulator.addFromDrop(cm.getC(), item, false);
                    cm.sendOk("恭喜你加卷成功！");
                    cm.喇叭(1, "恭喜玩家["+ cm.getName() + "]装备诅咒加卷+" + count + "成功！获得了装备<" + itemName + "+" + totalSlots + ">");
                } else {
                    var failureTxt = "很遗憾，你的强化失败了……"
                    var failureNotice = "很遗憾，玩家["+ cm.getName() + "]装备诅咒加卷失败……"

                    var roll = Math.random()
                    var boom = 1.0 / 2;
                    // 装备爆掉
                    if (roll < boom){ 
                        failureTxt += "而且很不幸，你的装备消失了……"
                        failureNotice += "伴随着一道光闪过，<" + itemName + "+" + totalSlots + ">化作了尘埃慢慢消失在了空气中……"
                        Packages.server.MapleInventoryManipulator.removeFromSlot(cm.getC(), Packages.client.inventory.MapleInventoryType.EQUIP, 1, 1, false);
                    }
                    cm.sendOk(failureTxt)
                    cm.喇叭(1, failureNotice);
                }
            } else {
                cm.sendOk("你选择的道具不足！");
            }
            cm.dispose()

        // 混沌加卷
        } else if (opt == 3) {
            // 设置用户选择的橡皮擦
            var selEraser = eraserMuyao
            if(selection == 1) { selEraser = eraserMuyao }
            else if(selection == 2) { selEraser = eraserMogu }
            else if(selection == 3) { selEraser = eraserHouzi }
            else if(selection == 4) { selEraser = eraserYouling }
            else if(selection == 5) { selEraser = eraserShuiling }
            else if(selection == 6) { selEraser = eraserZhangyu }
            
            if( cm.haveItem(goldenLeaf, needChaos) && cm.haveItem(selEraser, 1) ) {
                cm.gainItem(goldenLeaf, -needChaos);
                cm.gainItem(selEraser, -1);
                
                var item = cm.getChar().getInventory(Packages.client.inventory.MapleInventoryType.EQUIP).getItem(1).copy();
                var itemName = cm.getItemName(item.getItemId())
                var lvSlots = item.getLevel()
                var slots = item.getUpgradeSlots()
                var totalSlots = lvSlots + slots // 未砸卷+已砸卷的总次数

                var chance = Math.random();
                if (chance < probabilityChaos) {
                    item.setUpgradeSlots((item.getUpgradeSlots() + 1));
                    totalSlots += 1
                    Packages.server.MapleInventoryManipulator.removeFromSlot(cm.getC(), Packages.client.inventory.MapleInventoryType.EQUIP, 1, 1, false);
                    Packages.server.MapleInventoryManipulator.addFromDrop(cm.getC(), item, false);
                    cm.sendOk("恭喜你加卷成功！");
                    cm.喇叭(1, "恭喜玩家["+ cm.getName() + "]装备混沌加卷+1成功！获得了装备<" + itemName + "+" + totalSlots + ">");
                } else {
                    // 随机[-10, +5]属性
                    var range = 5 - Math.random() * 15
                    var count = Math.round(range)

                    item.setStr(item.getStr()+count)
                    item.setDex(item.getDex()+count)
                    item.setInt(item.getInt()+count)
                    item.setLuk(item.getLuk()+count)
                    item.setHp(item.getHp()+count)
                    item.setMp(item.getMp()+count)
                    item.setWatk(item.getWatk()+count)
                    item.setMatk(item.getMatk()+count)
                    item.setWdef(item.getWdef()+count)
                    item.setMdef(item.getMdef()+count)
                    item.setAcc(item.getAcc()+count)
                    item.setAvoid(item.getAvoid()+count)
                    item.setSpeed(item.getSpeed()+count)
                    item.setJump(item.getJump()+count)
                    Packages.server.MapleInventoryManipulator.removeFromSlot(cm.getC(), Packages.client.inventory.MapleInventoryType.EQUIP, 1, 1, false);
                    Packages.server.MapleInventoryManipulator.addFromDrop(cm.getC(), item, false);
                    
                    var attr = ""
                    if(count >= 0) { 
                        attr = "+" + count 
                    } else { 
                        attr = count }
                    cm.sendOk("很遗憾，你的加卷失败了，装备全属性随机" + attr)
                    cm.喇叭(1, "很遗憾，玩家["+ cm.getName() + "]装备混沌加卷失败……装备周围覆盖了一层迷雾……迷雾散去后，装备的样子发生了一些变化，<" + itemName + ">全属性"+attr);
                }
            } else {
                cm.sendOk("你选择的道具不足！");
            }
            cm.dispose()
        }
    }
}